from django.shortcuts import render

# Create your views here.
from django.core.paginator import Paginator
from django.http import JsonResponse

from django.db.models import Q
# Create your views here.
from django import forms
from django.forms import ModelForm
from django.http import HttpResponse
from django.forms.models import model_to_dict
from .models import Demo
import random
import re
import os 
import json
from datetime import datetime
from datetime import date

from django.conf import settings 
from fontTools.misc.py23 import basestring
from django.db.models.expressions import OrderBy


def pageNotFound(request):
    ''' 
    404、500处理函数
    '''
    return JsonResponse({'result': 200, 'info': '网页未能找到'})


def geturl(request):
    url = request.POST.get('url', '')
    title = request.POST.get('title', '')
    tid = request.POST.get('id', '')
    print(' 获得路径是....', url, '...title..', title, '...id...', tid)
    return JsonResponse({'code': 20000, 'data':{'name':title, 'url': url}})


def writeFile(obj, *paths):
    fixPath = ''
    for p in paths:
        if p != '':
            fixPath += os.sep + p
    fixPath = re.sub('^.', '', fixPath)     
    fixName = datetime.now().strftime('%H%M%S%f') + '1' + obj.name   
    print('....执行了函数 获得路径....', '...\n....', fixPath)
    path = os.path.join(settings.UPLOADFILES_DIRS, fixPath)
    if not os.path.exists(path):
        os.makedirs(path)
    f = open((path + fixName), 'wb')
    for i in obj.chunks():
        f.write(i)
    f.close()
    # if isinstance(urlOrPath, basestring):
    #     path = ' 字符串- ' + path        
    return fixPath, fixName


def upload(request):
    if request.method == 'POST':  # 获取对象
        obj = request.FILES.get('upfs', None)
        if not obj:
            return JsonResponse({'code': 20000, 'url': ''})

        fixPath, fixName = writeFile(obj, request.POST.get('id', ''), request.POST.get('title', ''), datetime.now().strftime('%Y%m%d') + '1')
        print('...函数调用...', fixPath)
    return JsonResponse({'code': 20000, 'data':{'name':fixName, 'url': fixPath + fixName}})


class DemoForm(ModelForm):
    date2 = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y', ])
#     date2 = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ'], widget=forms.DateTimeInput(attrs={'type': 'datetime-local', 'class': 'form-control'}, format='%Y-%m-%dT%H:%M:%S.%fZ'))

    class Meta:
        model = Demo
        fields = ['id', 'name', 'region', 'imgs', 'date2', 'delivery', 'classify', 'resource', 'remarks']


class DateJsonEncoder(json.JSONEncoder):

    def default(self, field):
        if isinstance(field, datetime):
            return field.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(field, date):
            return field.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, field)


def writeText(txt, *paths):
    fixPath = ''
    for p in paths:
        if p != '':
            fixPath += os.sep + p
    fixPath = re.sub('^.', '', fixPath)     
    fixName = datetime.now().strftime('%H%M%S%f') + '1.txt'   
    print('....执行了函数 获得路径....', '...\n....', fixPath)
    path = os.path.join(settings.UPLOADFILES_DIRS, fixPath)
    if not os.path.exists(path):
        os.makedirs(path)
        
    with open((path + os.sep + fixName), 'w') as f:
        f.write(txt)
    f.close()
    return fixPath, fixName


def crerateorupdate(request):
    tempData = request.POST.copy()
    tempId = tempData['id']
    # resource = request.POST.get('resource', '')
    print('这里打印id......' + tempId)
    
    if tempId == '':
        characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
        random_id = ''
        for _ in range(32):
            random_id += random.choice(characters)
        tempData['id'] = random_id

    if tempData['resource'] != '':
        path, name = writeText(tempData['resource'], tempData['name'], tempData['id'])
        print('......保存路径是.....', path + os.sep + name)
        tempData['resource'] = path + os.sep + name
       
    tempDemo = DemoForm(tempData)
    if tempId == '':
        print('.......组合的结果是......', tempData)
        tempDemo.save()
    else:
        Demo.objects.filter(pk=tempId).update_or_create(tempDemo.data)
        print("...文章是.....", tempDemo.data['resource'])
    return JsonResponse({'code': 20000, 'rId': tempDemo.data['id']})


def delete(request):
    tempId = request.POST.get('id')
    deleteDemo = Demo.objects.get(pk=tempId)
    deletedCount = deleteDemo.delete()[0]
    return JsonResponse({'code': 20000, 'deletedCount':deletedCount})


def queryList(request):
    q, res = Q(), []
    
    idString = request.GET.get('id', '')
    if idString:
        q.children.append(Q(**{'id':idString}))
    
    nameString = request.GET.get('name', '')
    if nameString:
        q.children.append(Q(**{'%s__contains' % "name":nameString}))
    
    regionString = request.GET.get('region', '')
    if regionString:
        q.children.append(Q(**{'%s__contains' % "region":regionString}))
        
    startString = request.GET.get('start', '')
    if startString:
        q.children.append(Q(**{'%s__gte' % "date1":datetime.strftime(datetime.strptime(startString, "%Y-%m-%d %H:%M:%S"), "%Y-%m-%d")}))
        
    endString = request.GET.get('end', '')
    if endString:
        q.children.append(Q(**{'%s__lte' % "date1":datetime.strftime(datetime.strptime(endString, "%Y-%m-%d %H:%M:%S"), "%Y-%m-%d")}))

    orderString = request.GET.get('orderBy', '')
    if  orderString:
        orderBy = re.sub(r'(\w+)\s+(ASC|DESC)', lambda x: "{}{}".format(('-' if x.group(2) == 'DESC' else ''), x.group(1),), orderString).split(",")
        querySet = Demo.objects.order_by(*orderBy).filter(q)
    else:
        querySet = Demo.objects.filter(q)
   
    pg = Paginator(querySet, (request.GET.get('pageSize', 10) if request.GET.get('pageSize') else 10))
    print(" q = ", q , "id =" , idString, "name = ", nameString, ".....region.....", regionString, ".....startString.....", startString, ".....endString.....", endString, ".....orderString.....", orderString)
    
    for originObjects in pg.page(request.GET.get('p', 1) if request.GET.get('p') else 1).object_list:
        originObjects.date1 = originObjects.date1.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        originObjects.date2 = originObjects.date2.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        res.append(model_to_dict(originObjects))
    
    return JsonResponse({'code': 20000, 'list':res, 'total':pg.count, })


def writeFile(obj, *paths):
    fixPath = ''
    for p in paths:
        if p != '':
            fixPath += os.sep + p
    fixPath = re.sub('^.', '', fixPath)     
    fixName = datetime.now().strftime('%H%M%S%f') + '1' + obj.name   
    print('....执行了函数 获得路径....', '...\n....', fixPath)
    path = os.path.join(settings.UPLOADFILES_DIRS, fixPath)
    if not os.path.exists(path):
        os.makedirs(path)
    f = open((path + fixName), 'wb')
    for i in obj.chunks():
        f.write(i)
    f.close()
    # if isinstance(urlOrPath, basestring):
    #     path = ' 字符串- ' + path        
    return fixPath, fixName


def upload(request):
    if request.method == 'POST':  # 获取对象
        obj = request.FILES.get('upfs', None)
        if not obj:
            return JsonResponse({'code': 20000, 'url': ''})

        fixPath, fixName = writeFile(obj, request.POST.get('id', ''), request.POST.get('title', ''), datetime.now().strftime('%Y%m%d') + '1')
        print('...函数调用...', fixPath)
    return JsonResponse({'code': 20000, 'data':{'name':fixName, 'url': fixPath + fixName}})
